package it.poste.il.compensatore.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import it.poste.il.compensatore.dao.UserDao;
import it.poste.il.compensatore.entity.User;

public class UserDaoImpl extends BaseEntityDaoImpl<User> implements UserDao {
    public UserDaoImpl() {
        super(User.class, "User");
    }

    public List<User> loadByFilter(User entityFilter) {
        throw new UnsupportedOperationException();
    }

    public User loadByExample(User entity) {
        throw new UnsupportedOperationException();
    }
    
	@Autowired(required=true)
	private SessionFactory sessionFactory;
	
	@Transactional()
	public User findById(String username) {
		this.sessionFactory.getCurrentSession().beginTransaction();
		return (User) this.sessionFactory.getCurrentSession().createQuery(
		"from User user where user.username=?").setParameter(0, username)
		.uniqueResult();
	}

	@Transactional
	public User saveOrUpdate(User user) {
		Transaction tx =  this.sessionFactory.getCurrentSession().beginTransaction();
		this.sessionFactory.getCurrentSession().saveOrUpdate(user);
		tx.commit();
		return user;
	}
	
	@Transactional
	public void delete(User user){
		Transaction tx =  this.sessionFactory.getCurrentSession().beginTransaction();
		this.sessionFactory.getCurrentSession().delete(user);
		tx.commit();
	}
	
	/*
	@Transactional
	public User findByCredential(String username, String password) {
		this.sessionFactory.getCurrentSession().beginTransaction();
		Object[] parameters = new Object[2];
		parameters[0]=username;
		parameters[1]=password;
		
		Type[] types = new Type[2];
		types[0]=Hibernate.STRING;
		types[1]=Hibernate.STRING;
		
		return (User) this.sessionFactory.getCurrentSession().createQuery(
		"from User user where (user.username=? and account.password=?)").setParameters(parameters, types).uniqueResult();
	}
	*/
}
